﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using QuanLyThuPhiTaiLieu.Model;

namespace QuanLyThuPhiTaiLieu.Biz
{
    public class DanhMucChiTietBiz : BaseBiz
    {
        public int SaveItem(DanhMucChiTiet item)
        {
            var dbContext = new Context();

            dbContext.DanhMucChiTiets.Add(item);
            int newId = dbContext.SaveChanges();

            return newId;
        }

        public void UpdateItem(DanhMucChiTiet item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public List<DanhMucChiTiet> ViewAll()
        {
            var dbContext = new Context();
            return (from item in dbContext.DanhMucChiTiets
                        orderby item.Sbq ascending
                        select item).ToList();
        }

        public List<DanhMucChiTietInfo> GetAllChiTiet(int parentId)
        {
            var dbContext = new Context();
            return (from item in dbContext.DanhMucChiTiets
                        join parent in dbContext.DanhMucs on item.Sbq equals parent.Id
                        where item.Sbq == parentId
                        orderby item.Sbq ascending
                        select new DanhMucChiTietInfo
                        {
                            Id = item.Id,
                            Sbq = item.Sbq,
                            Sdvbq = item.Sdvbq,
                            Anh = item.Anh,
                            Ban = item.Ban,
                            Can = item.Can,
                            Hinh = item.Hinh,
                            Kh = item.Kh,
                            Khn = item.Khn,
                            Manh = item.Manh,
                            PhanLoai = item.PhanLoai,
                            SbqValue = parent.Sqb,
                            Tptl = item.Tptl,
                            Trang = item.Trang
                        }).ToList();            
        }

        public DanhMucChiTiet LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.DanhMucChiTiets
                    where item.Id == id
                    select item).First();
        }

        public void RemoveItem(List<DanhMucChiTiet> items)
        {
            var dbContext = new Context();
            foreach (var tailieu in items)
            {
                dbContext.DanhMucChiTiets.Attach(tailieu);
                dbContext.DanhMucChiTiets.Remove(tailieu);
                dbContext.Entry(tailieu).State = EntityState.Deleted;
            }

            dbContext.SaveChanges();
        }
                
    }
}
